package com.david.core.utils

import android.app.Application
import android.os.Parcelable
import com.tencent.mmkv.MMKV

object MMKVUtil {
    private lateinit var mKv:MMKV

    /**
     * 使用时先调用init方法，传入application初始化mmkv
     */
    fun init(application: Application){
        if (this::mKv.isInitialized) {
            return
        }
        MMKV.initialize(application)
        mKv = MMKV.defaultMMKV()
    }

    fun put(key: String, value: Any) {
        when (value) {
            is Int -> mKv.encode(key, value)
            is String -> mKv.encode(key, value)
            is Boolean -> mKv.encode(key, value)
            is Float -> mKv.encode(key, value)
            is Long -> mKv.encode(key, value)
            is Double -> mKv.encode(key, value)
            is Parcelable -> mKv.encode(key, value)
        }
    }

    fun putString(k: String, v: String){
        mKv.encode(k, v)
    }

    fun putInt(k: String, v: Int){
        mKv.encode(k, v)
    }

    fun putBoolean(k: String, v: Boolean){
        mKv.encode(k, v)
    }

    fun putFloat(k: String, v: Float){
        mKv.encode(k, v)
    }

    fun putLong(k: String, v: Long){
        mKv.encode(k, v)
    }

    fun putDouble(k: String, v: Double){
        mKv.encode(k, v)
    }

    fun putParcelable(k: String, v: Parcelable){
        mKv.encode(k, v)
    }

    fun getString(k: String, def: String = ""): String {
        return mKv.decodeString(k, def) ?: def
    }

    fun getInt(k: String, defaultValue: Int = 0): Int {
        return mKv.decodeInt(k, defaultValue)
    }

    fun getBoolean(k: String, defaultValue: Boolean = false): Boolean {
        return mKv.decodeBool(k, defaultValue)
    }

    fun getFloat(k: String, defaultValue: Float = 0f): Float {
        return mKv.decodeFloat(k, defaultValue)
    }

    fun getLong(k: String, defaultValue: Long = 0): Long {
        return mKv.decodeLong(k, defaultValue)
    }

    fun getDouble(k: String, defaultValue: Double = 0.0): Double {
        return mKv.decodeDouble(k, defaultValue)
    }


    fun <T : Parcelable> getParcelable(k: String, clz: Class<T>): T? {
        return mKv.decodeParcelable(k, clz)
    }

    fun removeKey(k: String) {
        mKv.removeValueForKey(k)
    }

    fun clear() {
        mKv.clearAll()
    }

    fun containsKey(k: String): Boolean {
        return mKv.containsKey(k)
    }
}